<?php

namespace app\admin\service;

use app\common\configs\CommonData;
use app\common\configs\SettingConf;
use app\common\model\commonModel;
use app\common\model\trCache;
use app\common\model\trSystemSet;
use app\common\util\ErrorCode;
use app\common\util\Tools;

class WxMiniPublishService
{
    private $returnData;
    private $params;
    private $mall_id = 0;

    public function __construct($data, $params){
        $this->returnData = $data;
        $this->params = $params;
        $this->mall_id = request()->mallData["id"];
    }

    // 检查更新
    public function checkUpdate(){
        if(empty($this->params["projectName"])){
            $this->returnData = ErrorCode::$errorCode["fail"];
            $this->returnData["msg"] = "项目名不存在";
            return $this->returnData;
        }
        $versionData = commonModel::getList(wxAppUpgradeTable, "version", ["mall_id" => request()->mallData["id"]], 1, 1, "create_time desc", false);
        $currentVersion = !empty($versionData) ? $versionData[0]["version"] : 0;
        $res = Tools::curl(CommonData::WX_MINI_PUBLISH_SERVER_URL.CommonData::$wxMiniPublishRoute['checkUpdate'], json_encode([
            "version" => $currentVersion, "projectName" => $this->params["projectName"]
        ], JSON_UNESCAPED_UNICODE));
        $result = json_decode(trim($res, chr(239) . chr(187) . chr(191)), true);
        if(isset($result["code"])) {
            if ($result['code'] != 0) {
                $results = ErrorCode::$errorCode["fail"];
                $results["msg"] = $result["msg"];
                return $results;
            } else {
                if ($result["status"] == '1') {
                    trCache::saveCache(["key" => "publish_" . $this->params['token'], "value" => [
                        "version" => $result["data"]['version'], "desc" => $result["data"]['remarks'], "projectName" => $this->params["projectName"]
                    ], "time" => 7200]); // 登录信息放缓存
                }
                return $result;
            }
        }else{
            return ErrorCode::$errorCode["fail"];
        }
    }

    public function handleData($data){
        $setting = trSystemSet::getValue(SettingConf::WX_CHAT_APP_CONFIG);
        if(empty($setting["appId"]) || empty($setting["wxMiniUploadKey"])){
            return ErrorCode::code("customized", "未配置小程序appId或者上传密钥");
        }
        $requestParams = [
            "projectName" => $data["projectName"], "version" => $data['version'], "appId" => $setting["appId"], "host" => request()->domain(),
            "SaaS_ID" => request()->mallData["id"], "serviceProviderTicket" => $setting['serviceProviderTicket']
        ];
        $result = Tools::curl(CommonData::WX_MINI_PUBLISH_SERVER_URL.CommonData::$wxMiniPublishRoute['invokeCode'], json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != 0){
            return ErrorCode::code('customized', "error，{$res["msg"]}");
        }
        $data["token"] = $res["data"];
        $data["certKey"] = $setting["wxMiniUploadKey"];
        $data["appId"] = $setting["appId"];
        trCache::saveCache(["key" => "publish_" . $this->params['token'], "value" => $data, "time" => 7200]); // 登录信息放缓存
        return $data;
    }

    // 预览码
    public function previewByMini(){
        $cacheData = trCache::getValue("value", ["key" => "publish_".$this->params["token"]]);
        if(empty($cacheData)){
            return ErrorCode::code("customized", "错误");
        }
        $cacheData = $this->handleData($cacheData);
        if(isset($cacheData["code"])){
            return $cacheData;
        }
        $cacheData["certKey"] = $cacheData["certKey"] ?: "";
        $requestParams = [
            "projectName" => $cacheData['projectName'], "appId" => $cacheData["appId"], "token" => $cacheData["token"], 'certKey' => $cacheData["certKey"],
            "desc" => $cacheData["desc"]
        ];
        $result = Tools::curl(CommonData::WX_MINI_PUBLISH_SERVER_URL.CommonData::$wxMiniPublishRoute['preview'], json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != "0"){
            $this->returnData = ErrorCode::$errorCode["fail"];
            $this->returnData["msg"] = isset($res["msg"]) ? $res["msg"] : "获取预览结果失败";
        }else {
            $this->returnData["data"] = $res["data"];
        }
        return $this->returnData;
    }

    // 发布
    public function publishByMini(){
        $cacheData = trCache::getValue("value", ["key" => "publish_".$this->params["token"]]);
        if(empty($cacheData)){
            return ErrorCode::code("customized", "错误");
        }
        $cacheData["certKey"] = $cacheData["certKey"] ?: "";
        $requestParams = [
            "projectName" => $cacheData['projectName'], "appId" => $cacheData["appId"], "token" => $cacheData["token"], 'certKey' => $cacheData["certKey"],
            "desc" => $cacheData["desc"], 'version' => $cacheData['version']
        ];
        $result = Tools::curl(CommonData::WX_MINI_PUBLISH_SERVER_URL.CommonData::$wxMiniPublishRoute['upload'], json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != "0"){
            $this->returnData = ErrorCode::$errorCode["fail"];
            $this->returnData["msg"] = isset($res["msg"]) ? $res["msg"] : "获取上传结果失败";
        }else {
            if(commonModel::getCount(wxAppUpgradeTable, ["version" => $cacheData['version'], "mall_id" => request()->mallData["id"]])){
                commonModel::toUpdate(wxAppUpgradeTable, [
                    "remarks" => $cacheData["desc"], "create_time" => date("Y-m-d H:i:s")
                ], ["version" => $cacheData['version'], "mall_id" => request()->mallData["id"]]);
            }else {
                commonModel::toAdd(wxAppUpgradeTable, [
                    "version" => $cacheData['version'], "mall_id" => request()->mallData["id"], "remarks" => $cacheData["desc"], "create_time" => date("Y-m-d H:i:s")
                ]);
            }
            $this->returnData = $res;
        }
        return $this->returnData;
    }
}